const Koa = require('koa');
const bodyParser = require('koa-bodyparser');
const json = require('koa-json');
const dotenv = require('dotenv');

// 加载环境变量
dotenv.config();

// 创建Koa应用
const app = new Koa();

// 数据库连接
const connectDB = require('./src/config/db');
connectDB();

// 中间件
app.use(bodyParser());
app.use(json());

// 路由
const userRoutes = require('./src/routes/userRoutes');
const testRoutes = require('./src/routes/testRoutes');
app.use(userRoutes.routes()).use(userRoutes.allowedMethods());
app.use(testRoutes.routes()).use(testRoutes.allowedMethods());

// 错误处理中间件
app.use(async (ctx, next) => {
    try {
        await next();
    } catch (error) {
        ctx.status = error.status || 500;
        ctx.body = {
            success: false,
            message: error.message || '服务器内部错误',
        };

        console.error(error);
    }
});

// 首页路由
app.use(async (ctx, next) => {
    if (ctx.path === '/' || ctx.path === '/api') {
        ctx.status = 200;
        ctx.body = {
            success: true,
            message: '欢迎使用 uni-movie-voice 后台服务',
            data: {
                version: '1.0.0',
                timestamp: new Date().toISOString()
            }
        };
        return;
    }
    await next();
});

// 404处理
app.use((ctx) => {
    ctx.status = 404;
    ctx.body = {
        success: false,
        message: '接口不存在',
    };
});

const PORT = process.env.PORT || 3000;

app.listen(PORT, () => {
    console.log(`服务器运行在端口 ${PORT}`);
});

module.exports = app;